import Router from 'koa-router'
import { isNil, cloneDeep } from 'lodash-es'
import $dayjs from 'dayjs'
import { promisePool } from '../database/mysql2/index.js'
export const router = new Router()

// 新增与更新前的检查，检查username是否重复
const updateBeforeInspect = async (body, ctx) => {
  const [nameRows] = await promisePool.query(
    `SELECT * FROM user_info WHERE username='${body.username}' AND id!='${body.id}'`
  )
  if (nameRows.length) {
    ctx.body = {
      code: 400,
      msg: '用户名称重复！'
    }
    return true
  }
}

// 新增用户数据
router.post('/api/v1/users', async function (ctx) {
  const body = ctx.request.body
  console.log(body)
  // 检查username是否重复
  if (await updateBeforeInspect(body, ctx)) return
  await promisePool.execute(
    `INSERT INTO user_info (username,gender,mobile,email,status,createTime) values("${
      body.username
    }","${body.gender || ''}","${body.mobile || ''}","${body.email || ''}",${
      body.status
    },"${+new Date()}")`
  )

  ctx.body = {
    code: 200,
    msg: '操作成功！',
    data: null
  }
})

const getQueryHandle = async (query) => {
  const keywords = isNil(query.keywords) ? '' : query.keywords
  let startTime = query.startTime
  let startStr = ''
  let endTime = isNil(query.endTime) ? '' : query.endTime
  let endStr = ''
  // const startTime = isNil(query.startTime) ? '' : query.startTime
  // const endTime = isNil(query.endTime) ? '' : query.endTime
  if (isNil(query.startTime)) {
    startStr = ''
  } else {
    startStr = `AND createTime>='${+new Date(startTime)}'`
  }
  if (isNil(query.endTime)) {
    endStr = ''
  } else {
    endStr = `AND createTime<='${+new Date(endTime)}'`
  }
  const status =
    isNil(query.status) || query.status === '' ? '0,1' : query.status
  const [rows] = await promisePool.query(
    `SELECT * FROM user_info WHERE status IN (${status}) AND username LIKE '%${keywords}%' OR mobile LIKE '%${keywords}%' ${startStr} ${endStr}`
  )
  return rows
}

const timeDeal = (dataList) => {
  return dataList.map((item) => {
    item.createTime = item.createTime
      ? $dayjs(item.createTime * 1).format('YYYY-MM-DD HH:mm:ss')
      : item.createTime
    item.updateTime = item.updateTime
      ? $dayjs(item.updateTime * 1).format('YYYY-MM-DD HH:mm:ss')
      : item.updateTime
    return item
  })
}

// 查询用户的信息-分页
router.get('/api/v1/users/page', async (ctx) => {
  const query = ctx.request.query
  // console.log(query)
  const dataList = await getQueryHandle(query)
  // console.log(dataList)
  let newList = dataList.slice(
    query.pageSize * (query.pageNum - 1),
    query.pageSize * query.pageNum
  )
  newList = timeDeal(newList)
  ctx.body = {
    code: 200,
    msg: '查询成功！',
    data: {
      list: newList,
      total: dataList.length
    }
  }
})

// 查询用户的信息-所有的
router.get('/api/v1/users/pages', async (ctx) => {
  const query = ctx.request.query
  // console.log(query)
  let dataList = await getQueryHandle(query)
  // console.log(dataList)
  dataList = timeDeal(dataList)
  ctx.body = {
    code: 200,
    msg: '查询成功！',
    data: dataList
  }
})

// 查询单个用户数据
router.get('/api/v1/users/:id/form', async function (ctx) {
  const params = ctx.request.params
  // console.log(params)
  const [rows] = await promisePool.query(
    `SELECT * FROM user_info WHERE id=${params.id}`
  )
  // console.log(rows)
  ctx.body = {
    code: 200,
    msg: '查询成功！',
    data: rows[0]
  }
})

// 更新数据用户的信息
router.put('/api/v1/users/:id', async function (ctx) {
  // const params = ctx.request.params
  const body = ctx.request.body
  // console.log(params)
  // console.log(body)
  // 检查name是否重复
  if (await updateBeforeInspect(body, ctx)) return
  await promisePool.execute(
    `UPDATE user_info SET username="${body.username}",gender="${
      body.gender
    }",mobile="${body.mobile || ''}",email="${body.email || ''}",status=${
      body.status
    },updateTime="${+new Date()}" WHERE id='${body.id}'`
  )
  ctx.body = {
    code: 200,
    msg: '操作成功！',
    data: null
  }
})

// 删除单个或多个数据的信息
router.delete('/api/v1/users/:id', async function (ctx) {
  const params = ctx.request.params
  // console.log(params)
  const [ResultSetHeader] = await promisePool.execute(
    `DELETE FROM user_info WHERE id IN (${params.id})`
  )
  console.log('ResultSetHeader=', ResultSetHeader)
  ctx.body = {
    code: 200,
    msg: '操作成功！',
    data: null
  }
})
